<script lang="ts" setup name="GoodsImage">
import { computed, ref } from 'vue'
import { useMouseInElement } from '@vueuse/core'
defineProps<{
  images?: string[]
}>()
const active = ref(0)
const target = ref(null)
const { isOutside, elementX, elementY } = useMouseInElement(target)
const position = computed(() => {
  let x = elementX.value - 100
  let y = elementY.value - 100
  // if (elementX.value <= 100) x = 0
  // if (elementY.value <= 100) y = 0
  if (x <= 0) x = 0
  if (y <= 0) y = 0
  //  400 是大容器 200是遮罩
  if (x >= 400 - 200) x = 200
  if (y >= 400 - 200) y = 200
  return {
    x,
    y
  }
})
</script>

<!-- 结构 加两个 
    大图上的遮罩 定位
    右侧放大镜图 定位
    向右移动 大图(背景图)是向左移动  修改背景图的背景定位 backgroundPostion: 100px 100px
    向下移动  大图向上移动   
    遮罩移动1px  backgroudPosition 移动-2px
 -->
<template>
  <div class="goods-image">
    <!-- 右侧盛放大图的容器 -->
    <div class="large" v-show="!isOutside"
      :style="[{ backgroundImage: `url(${images?.[active]})` }, { backgroundPosition: `${-position.x * 2}px ${-position.y * 2}px` }]">
    </div>
    <!-- 左侧大图 -->
    <div class="middle" ref="target">
      <!-- 遮罩 -->
      <div class="layer" v-show="!isOutside" :style="{
        left: position.x + 'px',
        top: position.y + 'px'
      }"></div>
      <img :src="images?.[active]" alt="" />
    </div>
    <!-- 右侧图片列表 -->
    <ul class="small">
      <li v-for="(item, index) in images" :key="item" :class="{ active: index === active }"
        @mouseenter="active = index">
        <img :src="item" alt="" />
      </li>
    </ul>
  </div>
</template>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500; // 是提高定位元素的层级 (右侧的大图永远在最上面显示)
  // 提升父元素的层级  在同一父元素下 z-index越大 层级越高 最上面显示

  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }

  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;

    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, .2);
      left: 0px;
      top: 0px;
      position: absolute;
    }
  }

  .small {
    width: 80px;

    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;

      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>